package com.practice.springboot_01_zwj.controller;

import com.practice.springboot_01_zwj.entity.AccountInfo;
import com.practice.springboot_01_zwj.service.LoginService;
import com.practice.springboot_01_zwj.entity.vo.R;
import com.practice.springboot_01_zwj.entity.vo.Result;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * ClassName: LoginController <br/>
 * Description: 针对于LoginController登录业务的控制器类 <br/>
 * date: 2024/1/19 9:14 <br/>
 * @author mky <br/>
 * @version v1.0 <br/>
 * @since JDK 17 <br/>
 */
@RestController
@CrossOrigin(value="http://localhost:8083",allowCredentials = "true")
public class LoginController {
    @Autowired
    private LoginService loginService;

//    /**
//     * 验证码初始化
//     * @param session
//     *   将初始化验证码存入session
//     * @return
//     *   返回验证码
//     */
//    @GetMapping("/initLogin")
//    public R<String> initLogin(HttpSession session){
//        String code=CheckUtil.captCha();
//        session.setAttribute("code",code);
//        return new R<>(Result.SUCCESS.getCode(),Result.SUCCESS.getMsg(),code);
//    }

    /**
     * 登录验证（只需用户名）支持 JSON 格式
     * @param loginRequest 登录请求对象
     * @param session 用于存储用户信息
     * @return 返回登录验证结果
     */
    @PostMapping(value = "/login",
            consumes = MediaType.APPLICATION_JSON_VALUE,
            produces = MediaType.APPLICATION_JSON_VALUE)
    public R<Object> login(
            @RequestBody LoginRequest loginRequest,
            HttpSession session) {

        String userName = loginRequest.getUserName();

        // 1. 获取账号信息
        AccountInfo accountInfo = loginService.getAccountInfoByName(userName);

        // 2. 检查账号是否存在
        if (accountInfo == null) {
            return new R<>(Result.WITHOUT_ACCOUNT, 1);
        }

        // 3. 检查账号状态 (delMark: 0-注销, 1-正常)
        if (accountInfo.getDelMark() == 0) {
            return new R<>(Result.ACCOUNT_LOGOUT, 3);
        }

        // 4. 登录成功
        session.setAttribute("login_user", accountInfo);

        // 创建包含用户信息的 Map
        Map<String, Object> userData = new HashMap<>();
        userData.put("userId", accountInfo.getUserId());
        userData.put("userName", accountInfo.getUserName());
//        userData.put("password", accountInfo.getPassword());
        userData.put("acName", accountInfo.getAcName());
        userData.put("cityName", accountInfo.getCityName());
        userData.put("oaName", accountInfo.getOaName());
        userData.put("phone", accountInfo.getPhone());

        return new R<>(Result.SUCCESS_LOGIN, userData); // 成功时返回 Map 对象
    }

    /**
     * 登录验证：带用户名和密码
     * @param loginRequest 登录请求对象
     * @param session 用于存储用户信息
     * @return 返回登录验证结果
     */
    @PostMapping(value = "/loginWithPass",
            consumes = MediaType.APPLICATION_JSON_VALUE,
            produces = MediaType.APPLICATION_JSON_VALUE)
    public R<Object> loginWithPass(
            @RequestBody LoginRequest loginRequest,
            HttpSession session) {

        String userName = loginRequest.getUserName();
        String password = loginRequest.getPassword();

        // 1. 获取账号信息
        AccountInfo accountInfo = loginService.getAccountInfoByNameAndPass(userName, password);

        // 2. 检查账号是否存在
        if (accountInfo == null) {
            return new R<>(Result.WITHOUT_ACCOUNT, 1);
        }

        // 3. 检查账号状态 (delMark: 0-注销, 1-正常)
        if (accountInfo.getDelMark() == 0) {
            return new R<>(Result.ACCOUNT_LOGOUT, 3);
        }

        // 4. 登录成功
        session.setAttribute("login_user", accountInfo);

        // 创建包含用户信息的 Map
        Map<String, Object> userData = new HashMap<>();
        userData.put("userId", accountInfo.getUserId());
        userData.put("userName", accountInfo.getUserName());
        userData.put("password", accountInfo.getPassword()); // 注意：这里返回的是加密后的密码
        userData.put("acName", accountInfo.getAcName());
        userData.put("cityName", accountInfo.getCityName());
        userData.put("oaName", accountInfo.getOaName());
        userData.put("phone", accountInfo.getPhone());

        return new R<>(Result.SUCCESS_LOGIN, userData); // 成功时返回 Map 对象
    }
    /**
     * 修改密码
     * @param changePasswordRequest 修改密码请求对象
     * @return 返回修改结果
     */
    @PostMapping(value = "/changePassword",
            consumes = MediaType.APPLICATION_JSON_VALUE,
            produces = MediaType.APPLICATION_JSON_VALUE)
    public R<Object> changePassword(@RequestBody ChangePasswordRequest changePasswordRequest) {

        String userName = changePasswordRequest.getUserName();
        String oldPassword = changePasswordRequest.getOldPassword();
        String newPassword = changePasswordRequest.getNewPassword();

        // 参数校验
        if (userName == null || userName.isEmpty()) {
            return new R<>(Result.INVALID_PARAM, "用户名不能为空");
        }

        if (oldPassword == null || oldPassword.isEmpty()) {
            return new R<>(Result.INVALID_PARAM, "旧密码不能为空");
        }

        if (newPassword == null || newPassword.isEmpty()) {
            return new R<>(Result.INVALID_PARAM, "新密码不能为空");
        }

        // 检查新旧密码是否相同
        if (oldPassword.equals(newPassword)) {
            return new R<>(Result.INVALID_PARAM, "新密码不能与旧密码相同");
        }

        // 执行密码修改
        boolean success = loginService.changePassword(userName, oldPassword, newPassword);

        if (success) {
            return new R<>(Result.SUCCESS, "密码修改成功");
        } else {
            return new R<>(Result.FAILS, "密码修改失败，请检查旧密码是否正确");
        }
    }

    /**
     * 账号退出
     * @param session 清空登录用户session
     * @return 返回统一返回格式
     */
    @GetMapping(value = "/logout", produces = MediaType.APPLICATION_JSON_VALUE)
    public R<Integer> logout(HttpSession session) {
        session.removeAttribute("login_user");
        return new R<>(Result.SUCCESS, 1);
    }

    /**
     * 获取当前登录用户信息
     * @param session 当前会话
     * @return 用户信息
     */
    @GetMapping(value = "/current-user", produces = MediaType.APPLICATION_JSON_VALUE)
    public R<AccountInfo> getCurrentUser(HttpSession session) {
        AccountInfo accountInfo = (AccountInfo) session.getAttribute("login_user");
        if (accountInfo != null) {
            return new R<>(Result.SUCCESS, accountInfo);
        }
        return new R<>(Result.WITHOUT_ACCOUNT, null);
    }

}
class LoginRequest {
    private String userName;
    private String password;
    public LoginRequest() {}
    public LoginRequest(String userName, String password) {
        this.userName = userName;
        this.password = password;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
}
class ChangePasswordRequest {
    private String userName;
    private String oldPassword;
    private String newPassword;
    public ChangePasswordRequest() {
    }
    public ChangePasswordRequest(String userName, String oldPassword, String newPassword) {
        this.userName = userName;
        this.oldPassword = oldPassword;
        this.newPassword = newPassword;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public String getOldPassword() {
        return oldPassword;
    }
    public void setOldPassword(String oldPassword) {
        this.oldPassword = oldPassword;
    }
    public String getNewPassword() {
        return newPassword;
    }
    public void setNewPassword(String newPassword) {
        this.newPassword = newPassword;
    }
}